#!/usr/bin/env node

import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import {
  CallToolRequestSchema,
  ListToolsRequestSchema,
} from "@modelcontextprotocol/sdk/types.js";
import axios from 'axios';
import fs from 'fs';
import path from 'path';

// 从环境变量获取 API token
const METASO_API_TOKEN = process.env.Metaso_API_KEY || process.env.METASO_API_TOKEN;
if (!METASO_API_TOKEN) {
  throw new Error('Metaso_API_KEY environment variable is required');
}

// 创建 MCP 服务器
const server = new Server(
  {
    name: "metaso-reader",
    version: "1.0.0",
  },
  {
    capabilities: {
      tools: {},
    },
  }
);

// 工具处理器：读取网页内容
server.setRequestHandler(ListToolsRequestSchema, async () => {
  return {
    tools: [
      {
        name: "read_webpage",
        description: "从指定URL读取网页内容并返回markdown格式",
        inputSchema: {
          type: "object",
          properties: {
            url: {
              type: "string",
              description: "要读取的网页URL"
            },
            saveToFile: {
              type: "boolean",
              description: "是否将内容保存到本地markdown文件",
              default: false
            },
            filename: {
              type: "string",
              description: "保存文件名（可选，默认为时间戳）"
            }
          },
          required: ["url"]
        }
      },
      {
        name: "read_multiple_urls",
        description: "从多个URL读取网页内容并返回markdown格式",
        inputSchema: {
          type: "object",
          properties: {
            urls: {
              type: "array",
              items: {
                type: "string"
              },
              description: "要读取的网页URL数组"
            },
            saveToFiles: {
              type: "boolean",
              description: "是否将内容保存到本地markdown文件",
              default: false
            },
            prefix: {
              type: "string",
              description: "保存文件前缀（可选）"
            }
          },
          required: ["urls"]
        }
      }
    ]
  };
});

// 处理工具调用
server.setRequestHandler(CallToolRequestSchema, async (request) => {
  switch (request.params.name) {
    case "read_webpage": {
      const { url, saveToFile, filename } = request.params.arguments as {
        url: string;
        saveToFile?: boolean;
        filename?: string;
      };

      try {
        const data = JSON.stringify({ url });
        const config = {
          method: 'post' as const,
          maxBodyLength: Infinity,
          url: 'https://metaso.cn/api/v1/reader',
          headers: {
            'Authorization': `Bearer ${METASO_API_TOKEN}`,
            'Accept': 'text/plain',
            'Content-Type': 'application/json'
          },
          data: data
        };

        const response = await axios.request(config);
        const content = response.data;

        let filePath = null;
        if (saveToFile) {
          const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
          const safeFilename = filename || `${url.replace(/[^a-zA-Z0-9]/g, '_')}-${timestamp}`;
          const outputFilename = `${safeFilename}.md`;
          
          fs.writeFileSync(outputFilename, content);
          filePath = path.resolve(outputFilename);
        }

        return {
          content: [
            {
              type: "text",
              text: `成功读取网页内容: ${url}\n\n${content.substring(0, 2000)}${content.length > 2000 ? '...' : ''}${filePath ? `\n\n内容已保存到: ${filePath}` : ''}`
            }
          ]
        };
      } catch (error) {
        return {
          content: [
            {
              type: "text",
              text: `读取网页失败: ${error instanceof Error ? error.message : String(error)}`
            }
          ],
          isError: true
        };
      }
    }

    case "read_multiple_urls": {
      const { urls, saveToFiles, prefix } = request.params.arguments as {
        urls: string[];
        saveToFiles?: boolean;
        prefix?: string;
      };

      try {
        const results = [];
        
        for (const url of urls) {
          const data = JSON.stringify({ url });
          const config = {
            method: 'post' as const,
            maxBodyLength: Infinity,
            url: 'https://metaso.cn/api/v1/reader',
            headers: {
              'Authorization': `Bearer ${METASO_API_TOKEN}`,
              'Accept': 'text/plain',
              'Content-Type': 'application/json'
            },
            data: data
          };

          const response = await axios.request(config);
          const content = response.data;

          let filePath = null;
          if (saveToFiles) {
            const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
            const safePrefix = prefix || 'batch';
            const safeFilename = `${safePrefix}-${url.replace(/[^a-zA-Z0-9]/g, '_')}-${timestamp}`;
            const outputFilename = `${safeFilename}.md`;
            
            fs.writeFileSync(outputFilename, content);
            filePath = path.resolve(outputFilename);
          }

          results.push({
            url,
            content: content.substring(0, 1000) + (content.length > 1000 ? '...' : ''),
            savedTo: filePath
          });
        }

        const summary = results.map((result, index) => 
          `${index + 1}. ${result.url}\n   ${result.content.substring(0, 200)}...${result.savedTo ? `\n   已保存到: ${result.savedTo}` : ''}`
        ).join('\n\n');

        return {
          content: [
            {
              type: "text",
              text: `成功读取 ${urls.length} 个网页:\n\n${summary}`
            }
          ]
        };
      } catch (error) {
        return {
          content: [
            {
              type: "text",
              text: `批量读取网页失败: ${error instanceof Error ? error.message : String(error)}`
            }
          ],
          isError: true
        };
      }
    }

    default:
      throw new Error("未知工具");
  }
});

// 启动服务器
async function main() {
  const transport = new StdioServerTransport();
  await server.connect(transport);
  console.error("Metaso Reader MCP server running on stdio");
}

main().catch((error) => {
  console.error("Server error:", error);
  process.exit(1);
});
